import { login, casLogin, getInfo } from '@/api/login'
import { getToken, removeToken, setToken } from '@/utils/auth'
import md5 from 'md5'
import { Message } from 'element-ui'

const user = {
  state: {
    token: getToken(),
    name: '',
    avatar: '',
    userInfo: {},
    roles: [],
    menuList: []
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_USERINFO: (state, info) => {
      state.userInfo = info
    },
    SET_MENULIST: (state, _list) => {
      const list = {}
      _list.forEach(i => {
        list[i.menu_code] = {
          menu_name: i.menu_name,
          menu_id: i.menu_id
        }
      })
      state.menuList = list
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      const password = md5(userInfo.password)
      return new Promise((resolve, reject) => {
        login(username, password, userInfo.code).then(response => {
          let type = 'error'
          if (response.code === 200) {
            const data = response.data
            type = 'success'
            setToken(data.token)
            commit('SET_TOKEN', data.token)
            // commit('SET_USERINFO', data.user)
            // commit('SET_MENULIST', data.menu)
          }
          Message({ type, message: response.msg })
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    CasLogin({ commit }, casConfig) {
      const serverToken = casConfig.st.trim()
      const service = casConfig.service.trim()
      return new Promise((resolve, reject) => {
        casLogin(serverToken, service).then(response => {
          let type = 'error'
          if (response.code === 200) {
            const data = response.data
            type = 'success'
            setToken(data.token)
            commit('SET_TOKEN', data.token)
            // commit('SET_USERINFO', data.user)
            // commit('SET_MENULIST', data.menu)
          }
          Message({ type, message: response.msg })
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo().then(response => {
          if (!response.data.user) {
            reject()
          }
          const data = response.data
          commit('SET_USERINFO', data.user)
          commit('SET_MENULIST', data.menu)
          // if (data.roles && data.roles.length > 0) { // 验证返回的roles是否是一个非空数组
          //   commit('SET_ROLES', data.roles)
          // } else {
          //   reject('getInfo: roles must be a non-null array !')
          // }
          // commit('SET_NAME', data.name)
          // commit('SET_AVATAR', data.avatar)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        commit('SET_TOKEN', '')
        commit('SET_USERINFO', '')
        removeToken()
        window.location.href = 'http://sfrz.zepc.edu.cn/cas/logout'

        // logout(state.token).then(() => {
        //   commit('SET_TOKEN', '')
        //   commit('SET_USERINFO', '')
        //   removeToken()
        //   resolve()
        // }).catch(error => {
        //   reject(error)
        // })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    },

    // 更新token有效期
    UpdateTokenExpires({ commit }, config) {
      return new Promise(resolve => {
        let currentToken = getToken()
        if (currentToken) {
          currentToken = window.atob(window.atob(currentToken))

          const expireTime = process.env.TOKEN_EXPIRES_TIME || 1800000
          const newTimeString = new Date(config.date).getTime() + expireTime

          currentToken = currentToken.replace(/#(\d+)$/, `#${newTimeString}`)

          currentToken = window.btoa(window.btoa(currentToken))

          setToken(currentToken)
          commit('SET_TOKEN', currentToken)
        }
        resolve(getToken())
      })
    }
  }
}

export default user
